package com.yonyou.cloud.member.config;

import com.yonyou.cloud.member.exceptions.EntityIdInstantiationException;
import com.yonyou.cloud.member.domainmodel.vo.EntityId;
import com.yonyou.cloud.member.domainmodel.vo.CouponId;
import com.yonyou.cloud.member.domainmodel.vo.MemberId;
import com.yonyou.cloud.member.libs.key.KeyGenerator;
import com.yonyou.cloud.member.libs.key.KeyRegistry;
import com.yonyou.cloud.member.libs.key.MockKeyGeneratorImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Configuration
public class MemberAutoConfig {
    @Bean
    public KeyGenerator keyGenerator() {
        KeyRegistry keyRegistry = new KeyRegistry() {
            private Map<Class<? extends EntityId>, Function<Long, ?>> ctorMap = new HashMap<>();

            @Override
            public <T extends EntityId> void register(Class<T> clazz) {
                ctorMap.put(clazz, EntityIdFactory.create(clazz));
            }

            @Override
            public <T extends EntityId> T createKey(Class<T> clazz, long id) {
                if (!ctorMap.containsKey(clazz)) {
                    throw new EntityIdInstantiationException("未找到构建方法，类型：" + clazz.getName());
                }
                return (T) ctorMap.get(clazz).apply(id);
            }
        };
        // EntityId scan
        keyRegistry.register(MemberId.class);
        keyRegistry.register(CouponId.class);
        return new MockKeyGeneratorImpl(keyRegistry);
    }
}
